import time

from django.core.cache import cache
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin


# 设置：cache.set(键,值,有效时间)
# 获取：cache.get(键)
class HelloMiddle(MiddlewareMixin):

    def process_request(self, request):
        ip = request.META.get('REMOTE_ADDR')

        requests = cache.get(ip, [])
        black_list = cache.get('black', [])

        if ip in black_list:
            return HttpResponse('明天的现在再来吧')

        while requests and (time.time() - requests[-1] > 60):
            requests.pop()

        requests.insert(0, time.time())
        cache.set(ip, requests, timeout=60)

        if len(requests) >= 60:
            black_list.append(ip)
            cache.set('black', black_list, timeout=60 * 60 * 24)
            return HttpResponse('小爬虫，黑屋里面见')

        if len(requests) >= 30:
            return HttpResponse('小爬虫回家睡觉吧')

    def process_exception(self, request, exception):
        return redirect(reverse('index'))
